import { PermissionModeEnum } from "@/enums/appEnum";
import store from "@/store";
import { filter } from "@/utils/helper/treeHelper";
import { isUrl } from "@/utils/is";
import { RouteRecordNormalized } from "vue-router";
import router, { Routers } from "..";
import { pathToRegexp } from 'path-to-regexp';

const staticMenus: Routers[] = [];


async function getAsyncMenus() {
  if (isBackMode()) {
    return store.getters.getBackMenuList.filter((item:Routers) => !item.meta?.hidden && !item.hidden);
  }
  if (isRouteMappingMode()) {
    return store.getters.getFrontMenuList.filter((item:Routers) => !item.meta.hidden);
  }
  return staticMenus;
}

export const getMenus = async (): Promise<Routers[]> => {
  const menus = await getAsyncMenus();
  if (isRoleMode()) {
    const routes = router.getRoutes();
    return filter(menus, basicFilter(routes));
  }
  return menus;
};

const getPermissionMode = () => {
  return store.getters['app/getProjectConfig'].permissionMode;
};
const isBackMode = () => {
  return getPermissionMode() === PermissionModeEnum.BACK;
};

const isRouteMappingMode = () => {
  return getPermissionMode() === PermissionModeEnum.ROUTE_MAPPING;
};

const isRoleMode = () => {
  return getPermissionMode() === PermissionModeEnum.ROLE;
};


function basicFilter(routes: RouteRecordNormalized[]) {
  return (menu: Routers) => {
    const matchRoute = routes.find((route) => {
      if (isUrl(menu.path)) return true;

      if (route.meta?.carryParam) {
        return pathToRegexp(route.path).test(menu.path);
      }
      const isSame = route.path === menu.path;
      if (!isSame) return false;

      if (!route.meta?.requiresAuth) return true;

      return isSame || pathToRegexp(route.path).test(menu.path);
    });

    if (!matchRoute) return false;
    menu.icon = (menu.icon || matchRoute.meta.icon) as string;
    menu.meta = matchRoute.meta;
    return true;
  };
}



